{% extends "admin/base_site_nav.html" %}
{% load i18n %}

{% block extrahead %}{{block.super}}

<script>
 
function render(data) {
  var grid = $("#grid");
  $("#reportmanager_test").prop('disabled', false);
  $("#reportmanager_cancel").prop('disabled', true); 
  if (!grid.is(':empty'))
    grid.jqGrid('GridUnload');
  if (data['status'] == "ok") {
  	$("#error").css('display','none');
	  grid.jqGrid({
	      colModel: data['colmodel'],
	      datatype: "local",
	      data: data['data'],
	      autowidth: true,
	      shrinkToFit: false,
	      iconSet: "fontAwesome",
	      guiStyle: "bootstrapPrimary",	      
	      autoencode: true,
	      scrollRows: true,
	      height: ($(window).height() - $("#grid").offset().top - 63 < 150) ? 150 : $(window).height() - $("#grid").offset().top - 63
	      });	  
  }
  else {
  	$("#error").css('display','block').text(data['status']);
  }
}

{% if perms.reportmanager.change_sqlreport or perms.reportmanager.add_sqlreport%}
function getSchema() {
	 $.ajax({
	    url: url_prefix + "/reportmanager/schema/",
	    type: 'GET',
	    datatype: "html",
	    success: function(data) {
	      $("#schemacolumn").html(data);
	      $("#schemacolumn .schema-header").click(function() {
          $(this).children("span.fa").toggleClass("fa-plus").toggleClass("fa-minus");
	      	$(this).next(".collapse").collapse("toggle");
	      });
	      $("a.schemafield").on("click", function(e) {
	      	var field = $(e.target).closest("a").find("code").first().text();
	      	if (field != "") {	      		
	      	  var statements = $("#reportmanager_statements");
	      		if (statements[0].selectionStart || statements[0].selectionStart === 0) {
	      	    var startPos = statements[0].selectionStart;
	      	    var endPos = statements[0].selectionEnd;
	      	    statements[0].value = statements[0].value.substring(0, startPos) +
	      	      field + ", " +
	      	      statements[0].value.substring(endPos, statements[0].value.length);
	      	    statements[0].selectionStart = startPos + field.length + 2;
	      	    statements[0].selectionEnd = startPos + field.length + 2;
	      	  } 
	      	else
	      	  this.value += field + ", ";
	      	}
	      });
	    },
	    async: true
	    });
}

function startEdit() {
	$("#editreport, #editbuttons").toggleClass("hidden");
	if ($("#schemacolumn").is(":empty")) getSchema();
}
{% endif %}

var xhr;

$(function() {

  $("#reportmanager_statements").resizable({
    handleSelector: "#resize-handle",
    resizeWidth: false,
    resizeHeight: true,
    onDrag: function(e) {
      $("#schemacolumn").height($("#reportmanager_statements").height());
    }
  });

  $("#reportmanager_statements").on("input", function() {
  	$("#reportmanager_save").removeClass("btn-primary").addClass("btn-danger");
    $(window).on('beforeunload', function() {
      if ($("#reportmanager_save").hasClass("btn-danger"))
        return 'There are unsaved changes.';
    });
  });
  
	$("#reportmanager_test").on("click", function(event) {
	  $("#reportmanager_test").prop('disabled', true);
	  $("#reportmanager_cancel").prop('disabled', false);
	  var sql = $("#reportmanager_statements");
	  xhr = $.ajax({
	    url: url_prefix + "/reportmanager/",
	    type: 'POST',
	    dataType: 'json',
	    data: {
	    	"sql": sql.val(),
	    	"test": true
	    },
	    success: render,
	    error: render,
	    async: true
	    });
	});
	
	var id = {% if report %}{{report.id}}{% else %}0{% endif %};
	
  $("#reportmanager_save").on("click", function(event) {
  	var data = {        
        "sql": $("#reportmanager_statements").val(),
        "save": true,
        "name": $("#id_name").val(),
        "public": $("#id_public").is(":checked"),
        "description": $("#id_description").val()
        };
  	if (id) data["id"] = id;
    xhr = $.ajax({
      url: url_prefix + "/reportmanager/",
      type: 'POST',
      dataType: 'json',
      data: data,
      async: true,
      success: function(data) {
        $("#workarea").prepend(
            '<div id="save_ok" class="row"><div class="col-md-12" style="margin-top: 5px">' 
            + '<ul class="alert alert-success"><li>{% trans "The report was saved successfully." %}</li>'
            + '</ul></div></div>'
            );
        setTimeout(function() {$("#save_ok").remove();}, 3000);
        $("#reportmanager_save").addClass("btn-primary").removeClass("btn-danger");
        id = data.id;
      }
      });
  });

	$("#reportmanager_format").on("click", function(event) {
    var sql = $("#reportmanager_statements");
    var data = sql.val();
    xhr = $.ajax({
      url: url_prefix + "/reportmanager/",
      type: 'POST',
      dataType: 'json',
      data: {
      	"sql": data,
      	"format": true
      	},
      success: function(data) {
      	sql.val(data['formatted']);
      },
      async: true
      });
  });

  {% if report %}
  $("#reportmanager_delete").on("click", function(event) {
    xhr = $.ajax({
      url: url_prefix + "/reportmanager/",
      type: 'POST',
      data: {
        "id": {{report.id}},
        "delete": true
        },
      success: function() {
      	window.location.href = url_prefix + "/data/reportmanager/sqlreport/";
      },
      async: true
      });
  });
  {% endif %}

	$("#reportmanager_cancel").on("click", function(event) {
		if (xhr) {
			xhr.abort();
		  xhr = null;
		  }
	});
	
	{% if report %}
  xhr = $.ajax({
      url: url_prefix + "/reportmanager/{{report.id}}/",
      type: 'GET',
      dataType: 'json',
      data: {"format": "json"},
      success: render,
      error: render,
      async: true
      });
	{% else %}
	getSchema();
	{% endif %}
});
</script>
{% endblock %}

{% block content %}

<div class="row form-group">

{% if perms.reportmanager.change_sqlreport %}
<div id="editbuttons" class="col-md-5{% if report %} hidden{% endif %}">
<button id="reportmanager_save" class="btn btn-primary">{% trans "save"|capfirst %}</button>
<button id="reportmanager_test" class="btn btn-primary">{% trans "test"|capfirst %}</button>
<button id="reportmanager_format" class="btn btn-primary">{% trans "format"|capfirst %}</button>
{% if report %}<button id="reportmanager_delete" class="btn btn-primary">{% trans "Delete" %}</button>{% endif %}
</div>
{% endif %}
 
{% if report %}
<div id="toolicons" class="col-xs-4 hor-align-right ver-align-middle pull-right"> 
  <button class="btn btn-xs btn-primary" onclick="grid.showExport(true)">
    <span data-toggle="tooltip" data-placement="top" title="" class="fa fa-arrow-down" data-original-title="{% trans 'export as CSV or Excel file'|capfirst|force_escape %}"></span>
  </button>
  <button class="btn btn-xs btn-primary" onclick="grid.showCustomize(false)">
    <span data-toggle="tooltip" data-placement="top" title="" class="fa fa-wrench" data-original-title="{% trans 'customize'|capfirst|force_escape %}"></span>
  </button>
  {% if perms.reportmanager.change_sqlreport and report.user == request.user %}
  <button class="btn btn-xs btn-primary" onclick="startEdit()" data-toggle="tooltip" data-placement="top" data-original-title="{% trans 'edit'|capfirst|force_escape %}">
    <span class="fa fa-pencil"></span>
  </button>
  {% endif %}
  <button class="btn btn-xs btn-primary" 
    onclick="window.open('{% setting "DOCUMENTATION_URL" %}/docs/{% version_short %}/user-guide/user-interface/report-manager.html');"
    data-toggle="tooltip" data-placement="top" data-original-title="{% trans 'help'|capfirst|force_escape %}">
    <span class="fa fa-question"></span>
  </button>
</div>
{% endif %}
</div>

<div id="editreport" {% if report %}class="hidden"{% endif %}>
<div class="row" style="padding-top:5px; padding-bottom:5px">
<div class="control-label col-md-2" style="text-align:right">
  <label class="required" style="font-weight:bold; color:#333" for="id_name">{% trans "name"|capfirst %}:</label>
</div>
<div class="controls col-md-10">
  <input type="text" name="name" class="form-control vTextField" maxlength="300" 
    placeholder="{% trans "name"|capfirst %}" value="{{report.name}}" required id="id_name">
</div>
</div>

<div class="row" style="padding-top:5px; padding-bottom:5px">
<div class="control-label col-md-2" style="text-align:right">
  <label for="id_description">{% trans "description"|capfirst %}:</label>
</div>
<div class="controls col-md-10">
  <input type="text" name="description" class="form-control vTextField" maxlength="500"
    placeholder="{% trans "description"|capfirst %}" id="id_description"
    {% if report.description %}value="{{report.description}}"{% endif %}>
</div>
</div>

<div class="row" style="padding-top:5px; padding-bottom:5px">
<div class="control-label col-md-2" style="text-align:right">
  <label for="id_public">{% trans "public"|capfirst %}:</label>
</div>
<div class="controls col-md-10">
  &nbsp;&nbsp;&nbsp;<input type="checkbox" style="transform: scale(1.5);" name="public" {% if report.public %}checked {% endif %}id="id_public">
</div>
</div>

<div class="row" style="text-align:center">
<div class="col-md-12">
<div id="sqlandschema" style="width:100%">
<table style="table-layout: fixed; width: 100%">
<tr>
<td style="padding-right: 5px">
<h4 style="text-align: left">{% trans "SQL query"|capfirst %}:</h4>
<textarea id="reportmanager_statements" rows="10"
 style="width: 100%; height:{% if request.prefs.height %}{{ request.prefs.height}}{% else %}200{% endif %}px; resize: none; font-size:1.25em; font-family:courier">
{{ report.sql }}
</textarea>
</td>
<td style="width:28em; padding-left:5px; padding-right:10px">
<h4>{% trans "schema"|capfirst %}</h4>
<div id="schemacolumn" style="overflow-y: scroll; height:{% if request.prefs.height %}{{ request.prefs.height}}{% else %}200{% endif %}px"></div>
</td>
</tr></table>
</div>
<span id="resize-handle" class="fa fa-bars handle" style="display: inline-block; touch-action: none"></span>
</div>
</div>

<!-- End editing section -->
</div>  

<div class="row">
<div class="col-md-12">
<div id="error"></div>
<div style="padding-right: 10px; width:100%">
<table id="grid" class="table table-striped" style="background-color: white"></table>
</div>
</div>
</div>
{% endblock %}
